package com.wk.wanjetpack

import android.os.Bundle
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import androidx.paging.ExperimentalPagingApi
import androidx.paging.LoadState
import com.wk.base.adapters.WkLoadStateAdapter
import com.wk.wanjetpack.adapters.MainListAdapter
import com.wk.wanjetpack.databinding.ActivityMainBinding
import com.wk.wanjetpack.viewmodels.MainViewModel
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch

@AndroidEntryPoint
class MainActivity : AppCompatActivity() {

    private val viewModel: MainViewModel by viewModels()
    private val mAdapter: MainListAdapter by lazy {
        MainListAdapter()
    }
    private lateinit var binding: ActivityMainBinding

    @ExperimentalPagingApi
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)
        binding.rvArticleList.adapter =
            mAdapter.withLoadStateHeaderAndFooter(header = WkLoadStateAdapter { mAdapter.retry() },footer = WkLoadStateAdapter{mAdapter.retry()})

        lifecycleScope.launchWhenCreated {
            mAdapter.loadStateFlow.collectLatest { loadStates ->
                binding.srlRefreshLayout.apply {
                    if (loadStates.refresh is LoadState.Loading) {
                        autoRefreshAnimationOnly()
                    } else {
                        closeHeaderOrFooter()
                    }
                }
            }
        }

        lifecycleScope.launchWhenCreated {
            requestListData()
        }
        binding.srlRefreshLayout.setOnRefreshListener {
            mAdapter.refresh()
        }

    }

    @ExperimentalPagingApi
    private fun requestListData() {
        lifecycleScope.launch {
            viewModel.requestListData()
                .collectLatest {
                mAdapter.submitData(it)
            }
        }
    }

}